<template>
    <view class="pay-container">
        <!-- 商品信息展示 -->
        <view class="order-goods" v-if="orderDetail.items && orderDetail.items.length">
            <template v-for="(item, index) in orderDetail.items" :key="index">
                <view v-if="item.itemType == 'B'" class="goods-item" >
                    <image class="goods-img" :src="item.proImg" mode="aspectFill"></image>
                    <view class="goods-info">
                        <view class="goods-name">{{item.proName}}</view>
                        <view class="goods-spec">规格：{{item.propertyName}}</view>
                        <view class="goods-period">租期：{{item.presPerNum}}期，每期30天</view>
                    </view>
                </view>
            </template>
        </view>
        <!-- 支付步骤 -->
        <view class="pay-steps">
            <view class="step" :class="{active: currentStep >= 1}">
                <text class="step-num">1</text>
                <text class="step-text">认证</text>
            </view>
            <template v-if="orderDetail.depositAmount > 0">
                <view class="step-line" :class="{active: currentStep >= 2}"></view>
                <view class="step" :class="{active: currentStep >= 2}">
                    <text class="step-num">2</text>
                    <text class="step-text">押金</text>
                </view>
            </template>
            <view class="step-line" :class="{active: currentStep >= 3}"></view>
            <view class="step" :class="{active: currentStep >= 3}">
                <text class="step-num">
                    {{ orderDetail.depositAmount > 0 ? '3' : '2' }}
                </text>
                <text class="step-text">签约</text>
            </view>
            <view class="refresh_status" >
                <view class="btn" @click="refreshOrderInfo"> 刷新订单 </view>
            </view>
        </view>
        <!-- 支付金额信息 -->
        <view class="pay-amount" v-if="currentStep === 2 || currentStep === 1">
            <template v-if="currentStep === 1">
                <view class="amount-title">认证服务费</view>
                <view class="amount-desc">本次签约服务费用主要用于确保租赁合同签约全程符合《中华人民共和国电子签名法》的相关要求，涵盖合同合法合规签约时产生的服务成本。若签约人退租或单方面取消合约，已支付的认证服务费用不予退还。</view>
                <view class="amount-value">¥{{orderDetail.offPayAmount}}</view>
            </template>
            <template v-if="currentStep === 2">
                <view class="amount-title">押金</view>
                <view class="amount-value">¥{{orderDetail.depositAmount}}</view>
            </template>
        </view>

        <!-- 支付方式选择 -->
        <view class="pay-methods" v-if="currentStep === 2 || currentStep === 1">
            <view class="method-title">选择支付方式</view>
            <view
                class="method-item"
                v-for="method in payTypeList"
                :key="method.id"
                :class="{active: actPayTypeId === method.payTypeId}"
                @click="selectPayMethod(method)"
            >
                <!-- <image :src="method.icon" mode="aspectFit" class="method-icon"></image> -->
                <view class="method-info">
                    <text class="method-name">{{ method.payTypeName }}</text>
                    <!-- <text class="method-desc">{{ method.desc }}</text> -->
                </view>
                <localRadio :value="actPayTypeId == method.payTypeId" readonly></localRadio>
            </view>
        </view>


        <view class="step3_form" v-if="currentStep === 3 && userAuthInfo.cycleInfo.cycleStatus == '00' && orderDetail.rentCycleState != '05'">
            <view class="form-title">请完善银行卡信息</view>
            <view class="form-item">
                <text class="label">姓名</text>
                <input type="text" v-model="bindCardForm1.accUserName" placeholder="请输入姓名" />
            </view>
            <view class="form-item">
                <text class="label">身份证号</text>
                <input type="text" v-model="bindCardForm1.accUserCardId" placeholder="请输入身份证号" />
            </view>
            <view class="form-item">
                <text class="label">银行名称</text>
                <input type="text" v-model="bindCardForm1.accBankName" placeholder="请输入开户银行名称" />
            </view>
            <view class="form-item">
                <text class="label">银行卡号</text>
                <input type="text" v-model="bindCardForm1.accNo" placeholder="请输入银行卡号" />
            </view>
            <view class="form-item">
                <text class="label">手机号</text>
                <input type="text" v-model="bindCardForm1.accMobile" placeholder="请输入银行预留手机号" />
            </view>
            <div class="flex bind_card_btn">
                <button class="submit-btn jump_bind_card" @click="jumpSignCard">跳过绑卡</button>
                <button class="submit-btn" :style="{background: agreeFlag ? '#1890ff' : '#ccc'}" @click="preSignSubmit">立即绑定</button>
            </div>
            <view style="margin-top: 50rpx;">
                <agreement v-model="agreeFlag" hasArtId >
                    <!-- <text @click="toArticle('767090921769533440', '《委托划扣授权书》')">《委托划扣授权书》 </text> -->
                    <!-- <text @click="toArticle('767082256098394112', '《银联卡关联关系管理服务协议》')">《银联卡关联关系管理服务协议》 </text> -->
                    <text @click="toArticle('746389971060916224', '《宝付支付服务协议》')">《宝付支付服务协议》 </text>
                    <!-- <text v-if="bindBankInfo.id" @click.stop="toArticle(bindBankInfo.id, bindBankInfo.name)"> 《{{ bindBankInfo.name }}》 </text> -->
                </agreement>
            </view>

        </view>



        <!-- 支付按钮 -->
        <view class="already_sign_order" v-if="orderDetail.rentDebitStatus == '01'">订单已签约</view>
        <view class="pay-action" v-else>
            <button v-if="currentStep === 1" class="pay-btn" @click="payStep1">支付认证费</button>
            <template v-if="currentStep === 2">
                <div v-if="orderDetail.depositSource" class="pay-btn zhima" @click="payStep2">
                    <image src="https://jdkj-1306681707.cos.ap-nanjing.myqcloud.com/S0000260/image/proImg_202505231011269767.png" class="zhima-icon"></image>
                    <span> 芝麻信用 | 免押金 </span>
                </div>
                <button v-else class="pay-btn" @click="payStep2">支付押金 </button>
            </template>
            <template v-if="currentStep === 3 && (userAuthInfo.cycleInfo.cycleStatus == '01' || orderDetail.rentCycleState == '05')">
                <button class="pay-btn" @click="payStep3({})">签约订单</button>
                <div class="sign_phone">
                    <p>手机：{{currentSignPhone.mobile}}</p>
                    <em v-if="currentSignPhone.authStatus != '01' || true" class="change_sign_phone" @click="changeSignPhone('open')">修改</em>
                </div>
                <div class="sign_phone" style="margin-top: 30rpx;">
                    <em @click="setJumpReg('open')" style="color: #999">手机号不可用？</em>
                </div>
            </template>
        </view>


        <!-- 短信验证码弹窗 -->
        <uni-popup ref="smsCodeDialogRef" type="center">
            <view class="sms-code-dialog">
                <view class="dialog-title">请输入验证码</view>
                <view class="phone-info">验证码已发送至：{{bindCardForm1.accMobile}}</view>
                <view class="input-box">
                    <input type="text" v-model="bindCardForm2.mobileCode" placeholder="请输入验证码" />
                </view>
                <view class="dialog-actions">
                    <button class="cancel-btn" @click="closeSmsDialog">取消</button>
                    <button class="confirm-btn" @click="confirmSmsCode">确定</button>
                </view>
            </view>
        </uni-popup>

        <uni-popup ref="jumpRegPopupRef" type="center">
            <view class="sms-code-dialog">
                <view class="dialog-title">快捷签约</view>
                <view style="margin-bottom: 40rpx;">进入签约界面后，请切换至 人脸识别认证 完成签约</view>
                <view class="dialog-actions">
                    <button class="cancel-btn" @click="setJumpReg('close')">取消</button>
                    <button class="confirm-btn" @click="payStep3({jumpReg: true})">去签约</button>
                </view>
            </view>
        </uni-popup>

        <!-- 短信验证码弹窗 -->
        <uni-popup ref="changePhoneDialogRef" type="center">
            <view class="sms-code-dialog">
                <view class="dialog-title">修改签约手机号</view>
                <view class="phone-info">当前手机号：{{currentSignPhone.mobile}}</view>
                <view class="input-box">
                    <input type="text" v-model="newSignPhone" placeholder="新手机号" />
                </view>
                <view class="dialog-actions">
                    <button class="cancel-btn" @click="changeSignPhone('cancel')">取消</button>
                    <button class="confirm-btn" @click="changeSignPhone('confirm')">确定</button>
                </view>
            </view>
        </uni-popup>

        <uni-popup ref="qrcodePayDialogRef" type="center">
            <view class="sms-code-dialog">
                <view class="dialog-title">微信/支付宝 扫一扫支付</view>
                <view class="qrcode_box">
                     <ikun-qrcode
                        class="qrcode"
                        width="450"
                        height="450"
                        unit="rpx"
                        color="#000000"
                        :data="qrcodeUrl"
                    />
                </view>
                <view class="tip">请截图保存二维码，5分钟内完成支付后返回刷新订单继续签约</view>
            </view>
        </uni-popup>

        <!-- <div>
            <button @click="openWeixinMiniApp">打开微信小程序</button>
            <button @click="openAlipayMiniApp">打开支付宝小程序</button>
        </div> -->
    </view>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { onLoad, onShow, onPullDownRefresh, onUnload } from '@dcloudio/uni-app'
import { orderInfo, getPayType, collect, userDepositPay,orderRentSign, createOrderContract,
    queryOrderContract, jumpRentCycleSign, qrCollectCancel, getUserContractInfo, changeUserContractInfo } from '@/api/order'
import { confirmBindCard, lockUserCyclePayApply, checkRentUserStatus } from '@/api/user'
import localRadio from "@/components/base/local-radio.vue";
import Interact from '@/utils/interact';
// import lQrcode from '@/components/qrcode/l-qrcode/l-qrcode.vue'
import ikunQrcode from '@/components/ikun-qrcode/components/ikun-qrcode/ikun-qrcode.vue';
import { useStore } from 'vuex';
import Agreement from '@/components/base/agreement.vue';
const Store = useStore();

const isDev = ref(process.env.NODE_ENV === 'development')

// 支付步骤
const currentStep = ref(1)

let orderNo = ''
onLoad((options: any) => {
    orderNo = options.orderNo
    getOrderInfo()
    getUserAuthInfo()
})

onShow(() => {
    getUserAuthInfo()
    if(orderDetail.value.orderNo) {
        getOrderInfo()
        getContractStatus()
    }
})



onUnload(() => {
    clearInterval(statusTimer)
})

onShow(() => {
    clearInterval(statusTimer)
})

onPullDownRefresh(async () => {
    await refreshOrderInfo()
    uni.stopPullDownRefresh()
})

const refreshOrderInfo = async () => {
    await getOrderInfo()
    if(orderDetail.value.orderNo) {
        getContractStatus()
    }
}


const userAuthInfo = ref<any>({
    cycleInfo: {},
    realNameInfo: {},
})
const getUserAuthInfo = () => {
    checkRentUserStatus({ }).then(res => {
        userAuthInfo.value = res.data
        bindCardForm1.value.accBankName = res.data.realNameInfo.FBankName || ''
        bindCardForm1.value.accNo = res.data.realNameInfo.FBankNo || ''
        bindCardForm1.value.accUserName = res.data.realNameInfo.realName || ''
        bindCardForm1.value.accUserCardId = res.data.realNameInfo.cardId || ''

        bindCardForm1.value.accMobile = res.data.cycleInfo.accMobile || ''
        bindCardForm1.value.applyId = res.data.cycleInfo.applyId || ''
        // bindCardForm1.value.accBankName = res.data.cycleInfo.accBankName || ''
        // bindCardForm1.value.accNo = res.data.cycleInfo.accNo || ''
        // bindCardForm1.value.accUserName = res.data.cycleInfo.accUserName || ''
        // bindCardForm1.value.accUserCardId = res.data.cycleInfo.accUserCardId || ''
    })
}


const orderDetail = ref<any>({})
const getOrderInfo = () => {
    return orderInfo({
        orderNo: orderNo,
    }).then(res => {
        orderDetail.value = res.data
        getCurrentSignPhone()
        getContractStatus()
        let isDelay = (orderDetail.value.extendData && orderDetail.value.extendData.delays && orderDetail.value.extendData.delays.length)
        if(isDelay || orderDetail.value.offPays && orderDetail.value.offPays.length > 0) {
            let isStep1Pay = orderDetail.value.offPays.some((i:any) => i.remark == 'step1pay') || isDelay
            // 这一行判断必须写在第一个if，因为有可能 depostiStatus == ’01‘ remark == 'step1pay',所以要先判断。
            // || orderDetail.value.offPays.some((i:any) => i.remark == 'step2pay')
            if(orderDetail.value.depostiStatus == '01' || (orderDetail.value.depositAmount == 0 && isStep1Pay)) {
                currentStep.value = 3
            } else if(isStep1Pay) {
                currentStep.value = 2
                getPayTypeList('ALIPAYAUTH')
            } else {
                currentStep.value = 1
                getPayTypeList('ALIMINI')
            }
        } else {
            currentStep.value = 1
            getPayTypeList('ALIMINI')
        }
    })
}

type PayType = 'ALIMINI' | 'ALIPAYAUTH'| 'WXMINI' | 'JHQRCODE'
type PayTypeItem = {
    preAppType?: 'WXMINI' | 'ALIMINI',
    payTypeId: string,
    payTypeName: string
}
const payTypeList = ref<any[]>([])
const actPayTypeId = ref('')
const getPayTypeList = async (paytype: PayType ) => {
    // #ifdef APP-PLUS
    payTypeList.value = [
        {
            preAppType: 'WXMINI',
            payTypeId: 'pre_weixin',
            payTypeName: '微信支付',
        },
        {
            preAppType: 'ALIMINI',
            payTypeId: 'pre_alipay',
            payTypeName: '支付宝支付',
        }
    ]
    actPayTypeId.value = payTypeList.value[0].payTypeId
    // #endif

    // #ifndef APP-PLUS
    let list = await getPayTypeApi(paytype)
    payTypeList.value = list
    actPayTypeId.value = list[0].payTypeId
    if(paytype == 'ALIMINI') {
        let codeList = await getPayTypeApi('JHQRCODE')
        // #ifdef H5
        if(navigator.userAgent.toLocaleLowerCase().indexOf('micromessenger') > -1) {
            payTypeList.value = codeList
            actPayTypeId.value = codeList[0].payTypeId
        } else {
            payTypeList.value.push(codeList[0])
        }
        // #endif

        // #ifndef H5
        payTypeList.value.push(codeList[0])
        // #endif
    }
    // #endif
}


const getPayTypeApi = (paytype: PayType ) => {
    return new Promise<PayTypeItem[]>((resolve, reject) => {
        getPayType({
            paytype: paytype,
            storeNo: orderDetail.value.storeNo//Store.state.shop.storeNo,
        }).then(res => {
            resolve(res.data)
        })
    })
}

// *************** 第一步 支付认证费 *****************



const qrcodePayDialogRef = ref<any>(null)
const qrcodeUrl = ref('')
const showQrcodePayDialog = (code:string) => {
    qrcodeUrl.value = code
    qrcodePayDialogRef.value.open()
}

const payCancel = () => {
    return qrCollectCancel({
        orderNo: orderNo,
    })
}

// 选择支付方式
const selectPayMethod = (method: any) => {
    actPayTypeId.value = method.payTypeId
}
// 处理支付
const payStep1 = async () => {
    if (!actPayTypeId.value) {
        return Interact.toast('请选择支付方式')
    }


    if(actPayTypeId.value == 'pre_alipay') {
        let payTypeItem = payTypeList.value.find((i:any) => i.payTypeId == actPayTypeId.value)
        let list = await getPayTypeApi(payTypeItem.preAppType)
        actPayTypeId.value = list[0].payTypeId
        openAlipayMiniApp()
        return
    }

    if(actPayTypeId.value == 'pre_weixin') {
        let payTypeItem = payTypeList.value.find((i:any) => i.payTypeId == actPayTypeId.value)
        let list = await getPayTypeApi(payTypeItem.preAppType)
        actPayTypeId.value = list[0].payTypeId
        openWeixinMiniApp()
        return
    }



    uni.showLoading({
        title: '加载中',
        mask: true,
    })

    collect({
        collectMoney: orderDetail.value.offPayAmount,
        orderNo: orderDetail.value.orderNo,
        payTypeId: actPayTypeId.value,
        FrontRemark: 'step1pay'
    }).then(res => {
        if(res.data.payType == 'JHQRCODE') {
            // #ifdef H5
            if(navigator.userAgent.toLocaleLowerCase().indexOf('micromessenger') > -1) {
                location.href = res.data.qrCodeUrl
            } else {
                showQrcodePayDialog(res.data.qrCodeUrl)
            }
            // #endif

            // #ifndef H5
            showQrcodePayDialog(res.data.qrCodeUrl)
            // #endif
        } else {
            my.tradePay({
                tradeNO: res.data.payData.ali_trade_no,
                success: async (res: any) => {
                    uni.hideLoading()
                    console.log('success', res);
                    if(res.resultCode == '6001') {
                        await payCancel()
                    }
                    getOrderInfo()
                },
                fail: (err: any) => {
                    console.log(err);
                    payCancel()
                    uni.hideLoading()
                    Interact.toast('支付失败')
                },
                complete: (res: any) => {
                    console.log(res, 'compleeeeeeee');
                }
            })

        }
    }, (err: any) => {
        uni.hideLoading()
        payCancel()
        Interact.toast(err.msg)
    })
}




// *************** 第二步 支付押金 *****************
// 处理支付
const payStep2 = async () => {
    if (!actPayTypeId.value) {
        return Interact.toast('请选择支付方式')
    }
    uni.showLoading({
        title: '加载中',
        mask: true,
    })
    userDepositPay({
        depositPlat: !orderDetail.value.depositSource ? 'ali' : '',
        collectMoney: orderDetail.value.depositAmount,
        orderNo: orderDetail.value.orderNo,
        payTypeId: actPayTypeId.value,
        // FrontRemark: 'step2pay'
    }).then(res => {
        my.tradePay({
            orderStr: res.data.payData.payUrl,
            success: (res: any) => {
                uni.hideLoading()
                getOrderInfo()
                console.log('success', res);
            },
            fail: (err: any) => {
                console.log(err);

                uni.hideLoading()
                Interact.toast('支付失败')
            },
        })


    }, (err: any) => {
        uni.hideLoading()
        Interact.toast(err.msg)
    })
}


// *************** 第三步 合同签约 *****************
const jumpRegPopupRef = ref()
const setJumpReg = (type: 'open' | 'close') => {
    if(type == 'open') {
        jumpRegPopupRef.value.open()
    } else {
        jumpRegPopupRef.value.close()
    }
}


let statusTimer = -1;
const signText = ref('订单签约')
const payStep3 = ( options: any ) => {
    if(contractStatus.value == '01') {
        doOrderRentSign()
    } else {
        let data: any = {
            orderNo: orderDetail.value.orderNo,
        }
        // #ifdef H5
        data.redirectUrl = location.origin + '/pages/order/contractSuccess?orderNo=' + orderDetail.value.orderNo
        // #endif

        // #ifndef H5
        data.miniRedirectUrl = '/pages/order/contractSuccess?orderNo=' + orderDetail.value.orderNo
        // #endif
        if(options.jumpReg) {
            data.jumpReg = '01'
        }
        console.log(data);
        createOrderContract(data, {
            noErrorToast: true
        }).then(res => {
            uni.navigateTo({
                url: `/pages/webview/webview?path=${encodeURIComponent(encodeURIComponent(res.data.actorSignTaskEmbedUrl))}`
                // url: `/pages/webview/webview?path=${encodeURIComponent(res.data.actorSignTaskEmbedUrl)}`
            })
            clearInterval(statusTimer)
            statusTimer = setInterval(() => {
                getContractStatus()
            }, 5000)
        }, err => {
            if(err.code == -2) {
                doOrderRentSign()
            } else {
                Interact.toast(err.msg)
            }
        })
    }
}

const doOrderRentSign = () => {
    orderRentSign({
        orderNo: orderDetail.value.orderNo,
    }, {
        noErrorToast: true
    }).then(res => {
        Interact.modal({
            title: '提示',
            message: '签约成功',
        }).then(() => {
            uni.switchTab({
                url: '/pages/index',
            })
        })
    }, err => {
        if(err.code == -3) {
            // 已签约
        } else {
            Interact.toast(err.msg)
        }
    })
}

const contractStatus = ref('00')
const getContractStatus = () => {
    queryOrderContract({
        orderNo: orderDetail.value.orderNo,
    }).then(res =>{
        contractStatus.value = res.data.contractStatus
        console.log(res.data.contractStatus, 'contractStatus');
        if(res.data.contractStatus == '01') {
            signText.value = '我已完成签约'
            doOrderRentSign()
            clearInterval(statusTimer)
        } else {
            signText.value = '订单签约'
        }
    })
}

const currentSignPhone = ref({
    id: '',
    mobile: '',
    authStatus: '', // 01已认证过的，不能修改手机号
})
const newSignPhone = ref('')
const changePhoneDialogRef = ref();

const getCurrentSignPhone = () => {
    getUserContractInfo({
        storeNo: orderDetail.value.storeNo,
    }).then(res => {
        currentSignPhone.value = res.data
    })
}

const changeSignPhone = (type: 'open'| 'cancel' | 'confirm') => {
    if(type == 'open') {
        changePhoneDialogRef.value.open()
    } else if(type == 'cancel') {
        newSignPhone.value = ''
        changePhoneDialogRef.value.close()
    } else if(type == 'confirm') {
        if(!newSignPhone.value) return Interact.toast('请输入新手机号')
        if(!/^1\d{10}$/.test(newSignPhone.value)) return Interact.toast('手机号格式不正确')
        changeUserContractInfo({
            id: currentSignPhone.value.id,
            mobile: newSignPhone.value,
        }).then(res => {
            Interact.toast('修改成功')
            changeSignPhone('cancel')
            getCurrentSignPhone()
        })
        console.log(newSignPhone.value);

    }
}





const bindCardForm1 = ref<any>({
    accBankName: '',
    accMobile: '',
    accNo: '',
    accUserCardId: '', // 身份证
    accUserName: '', //姓名
    applySource: 'baofu',
    accType: '00',
    applyId: '',
})
const bindCardForm2 = ref<any>({
    mobileCode: '',
})
let bindCardInfo = {
    applyId: '',
    preId: '',
}

const agreeFlag = ref(false)
const bindBankInfo: any = computed(() => {

    let bmap = [
        {
            key: '工商',
            name: '中国工商银行快捷支付业务服务协议' ,
            id: '767077735716618240'
        },
        {
            key: '建设',
            name: '中国建设银行非银行支付机构快捷支付业务个人信息授权协议' ,
            id: '767078174918967296'
        },
        {
            key: '华夏',
            name: '华夏银行快捷支付服务协议' ,
            id: '767077855359139840'
        },
        {
            key: '交通',
            name: '交通银行借记卡快捷支付服务协议' ,
            id: '767079003306590208'
        },
        {
            key: '民生',
            name: '中国民生银行借记卡快捷支付业务用户协议' ,
            id: '767079391762055168'
        },
        {
            key: '农业',
            name: '中国农业银行快捷支付授权扣款三方协议' ,
            id: '767079646205313024'
        },
        {
            key: '平安',
            name: '平安银行快捷支付服务协议（第三方机构专用）' ,
            id: '767079747640360960'
        },
        {
            key: '兴业',
            name: '兴业银行信用卡/借记卡快捷支付业务线上服务协议' ,
            id: '767079852007227392'
        },
        {
            key: '邮政',
            name: '中国邮政储蓄银行借记卡快捷支付业务线上服务协议' ,
            id: '767080112142155776'
        },
        {
            key: '浙商',
            name: '浙商银行银行卡快捷支付业务服务协议' ,
            id: '767080286314823680'
        },
        {
            key: '中国银行',
            name: '中国银行股份有限公司借记卡快捷支付服务协议' ,
            id: '767081590336520192'
        },
        {
            key: '中信',
            name: '中信银行借记卡快捷支付线上服务协议' ,
            id: '767081696653737984'
        },
        {
            key: '浦东发展',
            name: '上海浦东发展银行个人网上快捷支付业务客户服务协议' ,
            id: '767082075709767680'
        },
        {
            key: '招商',
            name: '招商银行借记卡银联无卡自助消费业务协议' ,
            id: '767082190415593472'
        },
    ]
    let bankInfo = bmap.find(i => {
        if(bindCardForm1.value.accBankName.indexOf(i.key) > -1) {
            return true
        } else {
            return false
        }
    })
    if(bankInfo) {
        return bankInfo
    } else {
        return {}
    }
})


const toArticle = (id: string, title: string) => {
    uni.navigateTo({
        url: '/pages/article/article?artId=' + id + '&title=' + title
    })
}
const preSignSubmit = () => {
    if(agreeFlag.value == false) {
        return Interact.toast('请阅读并勾选协议')
    }
    if(!bindCardForm1.value.accBankName) {
        return Interact.toast('请输入开户银行名称')
    }
    if(!bindCardForm1.value.accNo) {
        return Interact.toast('请输入银行卡号')
    }
    if(!bindCardForm1.value.accMobile) {
        return Interact.toast('请输入银行卡预留手机号')
    }

    if(bindCardForm1.value.accBankName.indexOf('招商') > -1) {
        return Interact.modal('目前不支持招商银行卡，请更换其他银行卡')
    }
    lockUserCyclePayApply({
        ...bindCardForm1.value,
    }).then(res => {
        smsCodeDialogRef.value.open()
        bindCardInfo = res.data
    })
}
const smsCodeDialogRef = ref()
// 关闭短信验证码弹窗
const closeSmsDialog = () => {
    smsCodeDialogRef.value.close()
}

const jumpSignCard = async () => {
    let action = await Interact.modal({
        title: '提示',
        message: '是否跳过银行卡直接签约？',
        showCancel: true,
    })
    if(action.confirm) {
        jumpRentCycleSign({
            orderNo: orderNo,
        }).then(() => {
            getOrderInfo()
            getUserAuthInfo()
        })
    }
}

// 确认短信验证码
const confirmSmsCode = () => {
    if (!bindCardForm2.value.mobileCode) {
        return Interact.toast('请输入验证码')
    }
    console.log(bindCardForm2.value.mobileCode);
    confirmBindCard({
        applyId: bindCardInfo.applyId,
        preId: bindCardInfo.preId,
        mobileCode: bindCardForm2.value.mobileCode,
    }).then(res => {
        smsCodeDialogRef.value.close()
        Interact.toast('绑定成功')
        getOrderInfo()
        getUserAuthInfo()
    }, err => {
        Interact.toast(err.msg)
    })
}





const getToAppPath = () => {
    let payTypeId = actPayTypeId.value
    let token = Store.state.user.account.token
    let orderNo = orderDetail.value.orderNo
    let price = orderDetail.value.offPayAmount

    let path =  `pages/app/pay?token=${token}&orderNo=${orderNo}&price=${price}&payTypeId=${payTypeId}&params=${JSON.stringify({
        FrontRemark: 'step1pay'
    })}`
    console.log(path);

    return path
}

const openAlipayMiniApp = () => {
    let pages = encodeURIComponent(getToAppPath()) //页面参数
    let query = encodeURIComponent('') //启动参数 a=1&b=2
    let appid = '2021005138671232'

    let alipayUrl;
    alipayUrl = `alipays://platformapi/startapp?appId=${appid}&page=${pages}&query=${query}`;
    // ios 需要配置白名单才能跳转
    plus.runtime.openURL(alipayUrl, function(res) {
        console.log('打开支付宝结果：' + JSON.stringify(res));
    });
}
const openWeixinMiniApp = () => {
    plus.share.getServices((res) => {
        console.log('suc', res);
        let weixin = res.find((i: any) => i.id == 'weixin')
        if(weixin) {
            weixin.launchMiniProgram({
                id: 'gh_9621f7213d1d',
                type: 0, //小程序版本  0-正式版； 1-测试版； 2-体验版。
                path: getToAppPath()
            })
        }
    }, err => {
        console.log('err',err);
    })
}

</script>

<style lang="scss" scoped>
.pay-container {
    padding: 30rpx;
    background: #f5f5f5;
    min-height: 100vh;
}

.pay-steps {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: center;
    margin-bottom: 30rpx;

    .step {
        display: flex;
        flex-direction: column;
        align-items: center;

        .step-num {
            width: 40rpx;
            height: 40rpx;
            border-radius: 50%;
            background: #ccc;
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24rpx;
            margin-bottom: 10rpx;
        }

        .step-text {
            font-size: 28rpx;
            color: #666;
        }

        &.active {
            .step-num {
                background: #1890ff;
            }
            .step-text {
                color: #1890ff;
            }
        }
    }

    .step-line {
        width: 100rpx;
        height: 2rpx;
        background: #ccc;
        margin: 0 20rpx;
        margin-bottom: 30rpx;

        &.active {
            background: #1890ff;
        }
    }

    .refresh_status{
        width: 100%;
        .btn{
            width: 150rpx;
            height: 60rpx;
            margin: 30rpx auto 0;
            border-radius: 10rpx;
            background: #1890ff;
            color: #fff;
            font-size: 24rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            // position: absolute;
            right: 20rpx;
            top: 20rpx;
        }
    }
}

.pay-amount {
    background: #fff;
    padding: 30rpx;
    border-radius: 12rpx;
    margin-bottom: 30rpx;

    .amount-title {
        font-size: 28rpx;
        color: #666;
        font-weight: bold;
        margin-bottom: 20rpx;
    }
    .amount-desc {
        font-size: 26rpx;
        color: #666;
        margin-bottom: 20rpx;
    }

    .amount-value {
        font-size: 48rpx;
        font-weight: bold;
        color: #ff4d4f;
    }
}

.pay-methods {
    background: #fff;
    padding: 30rpx;
    border-radius: 12rpx;

    .method-title {
        font-size: 28rpx;
        color: #666;
        margin-bottom: 20rpx;
    }

    .method-item {
        display: flex;
        align-items: center;
        padding: 20rpx 0;
        border-bottom: 1rpx solid #f5f5f5;

        &:last-child {
            border-bottom: none;
        }

        .method-icon {
            width: 60rpx;
            height: 60rpx;
            margin-right: 20rpx;
        }

        .method-info {
            flex: 1;

            .method-name {
                font-size: 28rpx;
                color: #333;
                margin-bottom: 6rpx;
            }

            .method-desc {
                margin-left: 8rpx;
                font-size: 24rpx;
                color: #999;
            }
        }

        &.active {
            .method-name {
                color: #1890ff;
            }
        }
    }
}

.already_sign_order{
    width: 100%;
    text-align: center;
    line-height: 100rpx;
    font-size: 30rpx;
    color: #666;
}

.pay-action {
    margin-top: 60rpx;
    padding: 0 30rpx;

    .pay-btn {
        width: 100%;
        height: 88rpx;
        background: #1890ff;
        color: #fff;
        border-radius: 44rpx;
        font-size: 32rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        &.zhima {
            color: #fff;
            .zhima-icon {
                width: 30rpx;
                height: 36rpx;
                flex-shrink: 0;
                margin-right: 12rpx;
            }
        }
    }
    .sign_phone{
        margin-top: 50rpx;
        font-size: 26rpx;
        color: #666;
        text-align: center;
        line-height: 1;
        margin-bottom: 30rpx;
        display: flex;
        justify-content: center;
        .change_sign_phone{
            color: #1890ff;
            margin-left: 10rpx;
        }
    }
}

.waiting-popup {
    background: #fff;
    padding: 40rpx;
    border-radius: 12rpx;
    display: flex;
    flex-direction: column;
    align-items: center;

    .loading-icon {
        width: 120rpx;
        height: 120rpx;
        margin-bottom: 20rpx;
    }

    .waiting-text {
        font-size: 28rpx;
        color: #666;
        margin-bottom: 30rpx;
    }

    .cancel-btn {
        width: 240rpx;
        height: 72rpx;
        border: 1rpx solid #ddd;
        border-radius: 36rpx;
        font-size: 28rpx;
        color: #666;
        display: flex;
        align-items: center;
        justify-content: center;
    }
}

.order-goods {
    background: #fff;
    padding: 20rpx;
    border-radius: 12rpx;
    margin-bottom: 30rpx;

    .goods-item {
        display: flex;
        padding: 20rpx 0;
        border-bottom: 1rpx solid #f5f5f5;

        &:last-child {
            border-bottom: none;
        }

        .goods-img {
            width: 160rpx;
            height: 160rpx;
            border-radius: 8rpx;
            margin-right: 20rpx;
        }

        .goods-info {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-between;

            .goods-name {
                font-size: 28rpx;
                color: #333;
                margin-bottom: 10rpx;
            }

            .goods-spec, .goods-period {
                font-size: 24rpx;
                color: #666;
                margin-bottom: 6rpx;
            }
        }
    }
}
.step3_form {
    background: #fff;
    padding: 30rpx;
    border-radius: 12rpx;
    margin-bottom: 30rpx;

    .form-title {
        font-size: 32rpx;
        color: #333;
        margin-bottom: 30rpx;
        font-weight: bold;
    }

    .form-item {
        margin-bottom: 20rpx;
        display: flex;
        align-items: center;

        .label {
            font-size: 28rpx;
            color: #333;
            margin-bottom: 10rpx;
            display: block;
            width: 150rpx;
        }

        input {
            width: 500rpx;
            height: 80rpx;
            border: 1rpx solid #ddd;
            border-radius: 8rpx;
            padding: 0 20rpx;
            font-size: 28rpx;
        }
    }

    .submit-btn {
        width: 100%;
        height: 88rpx;
        background: #1890ff;
        color: #fff;
        border-radius: 44rpx;
        font-size: 32rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: 40rpx;
    }
    .bind_card_btn{
        display: flex;
        .submit-btn{
            flex: 1;
        }
        .jump_bind_card{
            width: 200rpx!important;
            flex: none!important;
            color: #333;
            background: #fff;
            border: 1px solid #ddd;
            margin-right: 20rpx;
        }
    }
}




.sms-code-dialog {
    background: #fff;
    width: 600rpx;
    border-radius: 12rpx;
    padding: 40rpx;

    .dialog-title {
        font-size: 32rpx;
        color: #333;
        text-align: center;
        margin-bottom: 30rpx;
        font-weight: bold;
    }

    .phone-info {
        font-size: 28rpx;
        color: #666;
        text-align: center;
        margin-bottom: 30rpx;
    }

    .input-box {
        margin-bottom: 40rpx;

        input {
            width: 100%;
            height: 80rpx;
            border: 1rpx solid #ddd;
            border-radius: 8rpx;
            padding: 0 20rpx;
            font-size: 28rpx;
            text-align: center;
        }
    }

    .dialog-actions {
        display: flex;
        justify-content: space-between;
        gap: 20rpx;

        button {
            flex: 1;
            height: 80rpx;
            border-radius: 40rpx;
            font-size: 28rpx;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .cancel-btn {
            background: #f5f5f5;
            color: #666;
        }

        .confirm-btn {
            background: #1890ff;
            color: #fff;
        }
    }

    .qrcode_box{
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .tip{
        width: 400rpx;
        color: #ff6600;
        font-size: 26rpx;
        margin: 0 auto;
    }
}
</style>
